package com.mjk.common.util;


import com.mjk.common.tools.logger.BizLogger;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.BitSet;

public class UrlEncoderUtils {
	private static final BitSet dontNeedEncoding;

	static {
		dontNeedEncoding = new BitSet(256);
		int i;
		for (i = 'a'; i <= 'z'; i++) {
			dontNeedEncoding.set(i);
		}
		for (i = 'A'; i <= 'Z'; i++) {
			dontNeedEncoding.set(i);
		}
		for (i = '0'; i <= '9'; i++) {
			dontNeedEncoding.set(i);
		}
		dontNeedEncoding.set('+');

        dontNeedEncoding.set('-');
		dontNeedEncoding.set('_');
		dontNeedEncoding.set('.');
		dontNeedEncoding.set('*');
	}

	/**
	 * 判断str是否urlEncoder.encode过<br>
	 * 经常遇到这样的情况，拿到一个URL,但是搞不清楚到底要不要encode.<Br>
	 * 不做encode吧，担心出错，做encode吧，又怕重复了<Br>
	 *
     */
	public static boolean hasUrlEncoded(String str) {
        boolean needEncode = false;
		int length = str.length();
		for (int i = 0; i < length; i++) {
			char c = str.charAt(i);
			if (dontNeedEncoding.get(c)) {
				continue;
			}
			if (c == '%' && (i + 2) < length) {
				// 判断是否符合urlEncode规范
				char c1 = str.charAt(i + 1);
				char c2 = str.charAt(i + 2);
				if (isDigit16Char(c1) && isDigit16Char(c2)) {
					continue;
				}
			}
			// 其他字符，肯定需要urlEncode
			needEncode = true;
			break;
		}
		return !needEncode;
	}

	/**
	 * 判断c是否是16进制的字符
	 *
     */
	private static boolean isDigit16Char(char c) {
		return (c >= '0' && c <= '9') || (c >= 'A' && c <= 'F');
	}

	public static String urlDecoder(String str, String charset) {
		try {
			return URLDecoder.decode(str, charset);
		} catch (UnsupportedEncodingException e) {
			BizLogger.error(e);
		}
		return "";
	}
	
	public static String urlEncode(String str, String charset) {
		try {
			return URLEncoder.encode(str, charset);
		} catch (UnsupportedEncodingException e) {
			BizLogger.error(e);
		}
		return "";
	}
}